package com;

import jline.console.ConsoleReader;
import jline.console.UserInterruptException;
import jline.console.completer.Completer;
import jline.console.history.History;

import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;

/**
 * @author 张述江
 * @date 2023-08-28
 */
public class LineReader extends ConsoleReader implements Closeable {
    private boolean interrupted;

    public LineReader(History history, Completer... completers) throws IOException {
        this.setExpandEvents(false);
        this.setBellEnabled(true);
        this.setHandleUserInterrupt(true);
        this.setHistory(history);
        this.setHistoryEnabled(false);

        for (Completer completer : completers) {
            this.addCompleter(completer);
        }

    }

    @Override
    public String readLine(String prompt, Character mask) throws IOException {
        this.interrupted = false;

        String line;
        try {
            line = super.readLine(prompt, mask);
        } catch (UserInterruptException var5) {
            this.interrupted = true;
            return null;
        }

        if (this.getHistory() instanceof Flushable) {
            ((Flushable) this.getHistory()).flush();
        }

        return line;
    }

    @Override
    public void close() {
        super.close();
    }

    public boolean interrupted() {
        return this.interrupted;
    }
}
